package com.cutthroatcreations.woodenrailway;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;

import com.cutthroatcreations.woodenrailway.Train.Year;
//import android.app.ProgressDialog;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.support.v4.app.Fragment;

public class SingleTrainFragment extends Fragment {

	private OnImageSelectedListener imageSelectedListener;
	private UpdateOwnedListener updateOwnedListener;
	private static final String TAG = "SingleTrain";
	private View view;
	private String currentYear;
	private TrainListAdapter tla = null;
	ContentWorker cw;
	Context context;
	Train train;
	ImageView mImageView;
	ScrollView scroller;
	TextView id;
	TextView name;
	TextView itemNumber;
	TextView synopsis;
	TextView years;
	CheckBox owned;
	Bitmap bitmap;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		view = (View) inflater.inflate(R.layout.single_train, container, false);
		// Get intent

		// Attach UI variables via id's from layout
		name = (TextView) view.findViewById(R.id.name);
		itemNumber = (TextView) view.findViewById(R.id.item_number);
		synopsis = (TextView) view.findViewById(R.id.synopsis);
		years = (TextView) view.findViewById(R.id.years);
		owned = (CheckBox) view.findViewById(R.id.owned);
		scroller = (ScrollView) view.findViewById(R.id.scroller);
		mImageView = (ImageView) view.findViewById(R.id.profile);
		

		return view;

	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		
	}

	// Function to update train fragment in
	// tablet landscape view
	public void updateTrain(int index, TrainListAdapter tla) {
		unsetListener();
		
		if(tla != null)
			this.tla = tla;
		
		train = null;
		currentYear = WoodenApplication.cYears[WoodenApplication.getYearIndex()];
		if (index >= 0) {
			train = WoodenApplication.getAllTrains().get(index);

			cw = new ContentWorker(getActivity(), train, currentYear);
			
			if (cw.isOwned()) {
				Log.i(TAG, "Owned");
				owned.setChecked(true);
			}else{
				Log.i(TAG, "Not Owned");
				owned.setChecked(false);
			}
			
			setListener();
			
			AsyncTask<Train, Void, Train> loadImageTask = new loadImage();
			loadImageTask.execute(train);

		}
	}

	public class loadImage extends AsyncTask<Train, Void, Train> {

		@Override
		protected void onPreExecute() {
			// progressDialog = ProgressDialog.show(getActivity(),
			// "LOADING TRAIN", "Please Wait....", true);
		};

		@Override
		protected Train doInBackground(Train... params) {

			Train t = params[0];
			t.setBitmap(decodeImage(t.getID(), t.getImageName()));
			return t;

		}

		// decodes image and scales it to reduce memory consumption
		private Bitmap decodeImage(int trainId, String imageName) {
			Log.i(TAG, "Here");
			String imgName = imageName.replace(")", "_");
			imgName = imgName.replace(" ", "%20");
			Log.i(TAG, "There");
			String imgUrl = CustomHttpClient.BASE_URL
					+ "image.php?width=300&height=300&image=img/" + trainId
					+ "/" + imgName;

			try {
				// Decode image size
				BitmapFactory.Options o = new BitmapFactory.Options();
				o.inJustDecodeBounds = true;
				BitmapFactory.decodeStream(
						(InputStream) new URL(imgUrl).getContent(), null, o);

				// The new size to scale to
				final int REQUIRED_SIZE = 70;

				// Find the correct scale value. It should be the power of 2.
				int scale = 1;
				while (o.outWidth / scale / 2 >= REQUIRED_SIZE
						&& o.outHeight / scale / 2 >= REQUIRED_SIZE)
					scale *= 2;

				// Decode with inSampleSize
				BitmapFactory.Options o2 = new BitmapFactory.Options();
				o2.inSampleSize = scale;
				return BitmapFactory.decodeStream(
						(InputStream) new URL(imgUrl).getContent(), null, o2);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Train t) {

			super.onPostExecute(t);
			train = t;
			bitmap = t.getBitmap();
			mImageView.setImageBitmap(bitmap);
			mImageView.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {

					imageSelectedListener.onImageSelected(train.getID());
				}
			});
			if (train != null) {
				Spanned span = Html.fromHtml(train.getSynopsis());
				String syn = span.toString().replace("&", "\n \n");
				// set TextView text from Train object
				name.setText("Name:" + "\n" + train.getName());
				itemNumber.setText("Item Number:" + "\n"
						+ train.getItemNumber());
				synopsis.setText(syn);
				String allYears = "Years: " + "\n";
				for (Year year : train.years) {
					allYears = allYears.concat(year.start_year + " - "
							+ year.end_year + "\n");
				}
				years.setText(allYears);
			}
			
			// progressDialog.dismiss();
		}

	}

	public void setListener(){
		owned.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				Log.i(TAG, "CHECKED");
				int result = cw.checked();
				if (result > -1) {
					if (result > 0)
						owned.setChecked(false);
					else
						owned.setChecked(true);
				}
				if(tla != null)
					tla.notifyDataSetChanged();
				updateOwnedListener.updateTextView(WoodenApplication.getYearIndex());
				
			}
		});
	}
	
	public void unsetListener(){
		owned.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				return;	
			}
		});
	}
	
	public interface OnImageSelectedListener {
		public void onImageSelected(int id);
	}
	
	public interface UpdateOwnedListener {
		public void updateTextView(int index);
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		try {
			updateOwnedListener = (UpdateOwnedListener) activity;
			imageSelectedListener = (OnImageSelectedListener) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString()
					+ " must implement OnImageSelectedListener");
		}
	}

}
